<?php

namespace app\admin\controller\cms;

use app\admin\model\cms\LiveCategoryModel;
use app\api\service\HuaWeiLive;
use app\api\service\TengxunSignatureUtil;
use app\common\controller\Backend;
use app\common\model\Config;
use Endroid\QrCode\QrCode;
use fast\Tree;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
use think\Url;

class Live extends Backend
{

    /**
     * Live模型对象
     * @var \app\admin\model\cms\Live
     */
    protected $model = null;
    protected $searchFields = 'id,title,description';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\cms\Live;

        $categoryList = LiveCategoryModel::field('id,platename')->select();
        $this->view->assign("categoryList", $categoryList);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $type = $this->request->request("type");

            //构造父类select列表选项数据
            $list = [];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $domain = $this->request->domain();//当前域名
            foreach ($list as $v) {
                $v['qr_code_img'] = '';//分享二维码
                //判断是否开始直播
                if ($v['is_start_live'] == 1) {
                    //讲直播详请接口url变成二维码
                    $url = "{$domain}/api/v2/plaza_post/getQrCodeLiveShow?id={$v['id']}";
                    // 创建新的QrCode实例
                    $qrCode = new QrCode($url);
                    // 设置二维码的大小和边距
                    $qrCode->setSize(300);
                    $qrCode->setMargin(10);
                    // 获取二维码的base64编码数据URI
                    // 将二维码保存为图片文件
                    $qrCode->writeFile('uploads/live/qr_code/path_to_save_qrcode.png');
                    // 输出base64图片地址
                    $v['qr_code_img'] = $qrCode->writeDataUri();
                }
            }

//            foreach ($this->categorylist as $k => $v) {
//                if ($search) {
//                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
//                        if ($type == "all" || $type == null) {
//                            $list = $this->categorylist;
//                        } else {
//                            $list[] = $v;
//                        }
//                    }
//                } else {
//                    if ($type == "all" || $type == null) {
//                        $list = $this->categorylist;
//                    } elseif ($v['type'] == $type) {
//                        $list[] = $v;
//                    }
//                }
//            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $params['live_stream_name'] = time() . rand(100, 999);

        $config = Config::where('group', 'live_config')->field('name,title,value')->select();
        $live_config = [];
        foreach ($config as $v) {
            $live_config[$v['name']] = $v['value'];
        }

        $params['push_url'] = $live_config['push_url'];//推流域名
        $params['pull_url'] = $live_config['pull_url'];//拉流域名
        $params['live_app_name'] = $live_config['app_name'];//直播AppName

        if (!$params['push_url'] || !$params['pull_url'] || !$params['live_app_name']) {
            $this->error('缺少推流/拉流/直播AppName');
        }
        //判断推流域名与拉流域名是否相同
        if ($params['push_url'] == $params['pull_url']) {
            $this->error('推流域名与拉流域名不能是同一个');
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        $huaWeiLive = new HuaWeiLive();//华为云直播服务类
        $tengxunmeet = new TengxunSignatureUtil();//腾讯会议服务类
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                //开始直播
                if (isset($values['is_start_live']) && $values['is_start_live'] == 1) {
                    $meetinfo = $tengxunmeet->createMeeting($item['title']);//创建腾讯会议
                    Log::error(print_r($meetinfo, true));

                    $values['meet_info'] = json_encode($meetinfo, JSON_UNESCAPED_UNICODE);//腾讯会议信息
                    $values['push_live_url'] = $huaWeiLive->createLiveUrl($item['push_url'], $item['live_app_name'], $item['live_stream_name'], 'push') ?? '';//生成鉴权直播URL
                    $values['live_url'] = $huaWeiLive->createLiveUrl($item['pull_url'], $item['live_app_name'], $item['live_stream_name'], 'pull') ?? '';

                    $push_address = 'rtmp://' . $item['push_url'] . '/' . $item['live_app_name'] . '/';
                    $push_password = str_replace($push_address, '', $item['push_live_url']);
                    $tengxunmeet->setliveStreamAddress($meetinfo['meeting_info_list'][0]['meeting_id'], $push_address, $push_password);//设置第三方直播推流地址
                }
                $count += $item->allowField(array_keys($values))->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 直播会议回放雷列表
     * @return string
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function play_replays()
    {
        $live = $this->model->where($this->model->getPk(), $this->request->param('id'))->find();
        $live_play_replays_url = $live['live_play_replays_url'];
        $live_play_replays_url = json_decode($live_play_replays_url,true);
        $data = current($live_play_replays_url);
        $data['media_start_time'] = date('Y-m-d H:i',($data['media_start_time'] / 1000));

        $this->view->assign("data", $data);
        return $this->view->fetch();
    }
}
